import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index, OneToMany } from 'typeorm';
import { RequestPhase, RequestStatus } from './copilot-types';
import { CopilotFieldMapping } from './copilot-field-mapping.entity';

@Entity('copilot_request_logs')
@Index(['requestId'], { unique: true })
@Index(['userId'])
@Index(['status'])
@Index(['createdAt'])
@Index(['currentPhase'])
export class CopilotRequestLog {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'request_id', length: 36, unique: true })
  @Index()
  requestId: string;

  @Column({ name: 'user_id', length: 100, nullable: true })
  userId: string;

  @Column({ name: 'user_ip', length: 45, nullable: true })
  userIp: string;

  @Column({ name: 'user_agent', length: 500, nullable: true })
  userAgent: string;

  @Column({ 
    type: 'enum', 
    enum: RequestStatus,
    default: RequestStatus.IN_PROGRESS 
  })
  status: RequestStatus;

  @Column({ 
    type: 'enum', 
    enum: RequestPhase,
    name: 'current_phase',
    default: RequestPhase.CLIENT_REQUEST 
  })
  currentPhase: RequestPhase;

  // === 第一环节：接收到客户端Claude请求 ===
  @Column({ name: 'client_request_headers', type: 'json', nullable: true })
  clientRequestHeaders: Record<string, any>;

  @Column({ name: 'client_request_body', type: 'json', nullable: true })
  clientRequestBody: Record<string, any>;

  @Column({ name: 'client_request_method', length: 10, nullable: true })
  clientRequestMethod: string;

  @Column({ name: 'client_request_url', length: 500, nullable: true })
  clientRequestUrl: string;

  @Column({ name: 'client_request_time', type: 'datetime', nullable: true })
  clientRequestTime: Date;

  // === 第二环节：请求转发到Copilot ===
  @Column({ name: 'copilot_request_headers', type: 'json', nullable: true })
  copilotRequestHeaders: Record<string, any>;

  @Column({ name: 'copilot_request_body', type: 'json', nullable: true })
  copilotRequestBody: Record<string, any>;

  @Column({ name: 'copilot_request_method', length: 10, nullable: true })
  copilotRequestMethod: string;

  @Column({ name: 'copilot_request_url', length: 500, nullable: true })
  copilotRequestUrl: string;

  @Column({ name: 'copilot_request_time', type: 'datetime', nullable: true })
  copilotRequestTime: Date;

  // === 第三环节：Copilot响应 ===
  @Column({ name: 'copilot_response_headers', type: 'json', nullable: true })
  copilotResponseHeaders: Record<string, any>;

  @Column({ name: 'copilot_response_body', type: 'json', nullable: true })
  copilotResponseBody: Record<string, any>;

  @Column({ name: 'copilot_response_status', type: 'int', nullable: true })
  copilotResponseStatus: number;

  @Column({ name: 'copilot_response_time', type: 'datetime', nullable: true })
  copilotResponseTime: Date;

  // === 第四环节：响应客户端请求 ===
  @Column({ name: 'client_response_headers', type: 'json', nullable: true })
  clientResponseHeaders: Record<string, any>;

  @Column({ name: 'client_response_body', type: 'json', nullable: true })
  clientResponseBody: Record<string, any>;

  @Column({ name: 'client_response_status', type: 'int', nullable: true })
  clientResponseStatus: number;

  @Column({ name: 'client_response_time', type: 'datetime', nullable: true })
  clientResponseTime: Date;

  // === 性能指标 ===
  @Column({ name: 'total_duration', type: 'int', comment: '总耗时(毫秒)', nullable: true })
  totalDuration: number;

  @Column({ name: 'conversion_duration', type: 'int', comment: '数据转换耗时(毫秒)', nullable: true })
  conversionDuration: number;

  @Column({ name: 'copilot_api_duration', type: 'int', comment: 'Copilot API耗时(毫秒)', nullable: true })
  copilotApiDuration: number;

  // === Token使用情况 ===
  @Column({ name: 'estimated_input_tokens', type: 'int', nullable: true })
  estimatedInputTokens: number;

  @Column({ name: 'estimated_output_tokens', type: 'int', nullable: true })
  estimatedOutputTokens: number;

  @Column({ name: 'actual_input_tokens', type: 'int', nullable: true })
  actualInputTokens: number;

  @Column({ name: 'actual_output_tokens', type: 'int', nullable: true })
  actualOutputTokens: number;

  // === 错误信息 ===
  @Column({ name: 'error_message', type: 'text', nullable: true })
  errorMessage: string;

  @Column({ name: 'error_stack', type: 'text', nullable: true })
  errorStack: string;

  @Column({ name: 'error_phase', type: 'enum', enum: RequestPhase, nullable: true })
  errorPhase: RequestPhase;

  // === 元数据 ===
  @Column({ name: 'model_name', length: 100, nullable: true })
  modelName: string;

  @Column({ name: 'service_name', length: 100, default: 'copilot-proxy' })
  serviceName: string;

  @Column({ name: 'api_version', length: 20, nullable: true })
  apiVersion: string;

  @Column({ name: 'is_streaming', type: 'boolean', default: false })
  isStreaming: boolean;

  @Column({ name: 'has_tools', type: 'boolean', default: false })
  hasTools: boolean;

  @Column({ name: 'retry_count', type: 'int', default: 0 })
  retryCount: number;

  // === 敏感信息标记 ===
  @Column({ name: 'contains_sensitive_data', type: 'boolean', default: false })
  containsSensitiveData: boolean;

  @Column({ name: 'data_redacted', type: 'boolean', default: false, comment: '数据是否已脱敏' })
  dataRedacted: boolean;

  @Column({ name: 'debug_info', type: 'json', nullable: true, comment: '调试信息' })
  debugInfo: Record<string, any>;

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;

  // === 关联关系 ===
  @OneToMany(() => CopilotFieldMapping, mapping => mapping.requestLog)
  fieldMappings: CopilotFieldMapping[];

  // === 便捷方法 ===
  
  /**
   * 获取请求的完整链路时间线
   */
  getTimeline() {
    return [
      { phase: RequestPhase.CLIENT_REQUEST, time: this.clientRequestTime, duration: 0 },
      { phase: RequestPhase.COPILOT_REQUEST, time: this.copilotRequestTime, 
        duration: this.copilotRequestTime && this.clientRequestTime ? 
          this.copilotRequestTime.getTime() - this.clientRequestTime.getTime() : null },
      { phase: RequestPhase.COPILOT_RESPONSE, time: this.copilotResponseTime,
        duration: this.copilotResponseTime && this.copilotRequestTime ?
          this.copilotResponseTime.getTime() - this.copilotRequestTime.getTime() : null },
      { phase: RequestPhase.CLIENT_RESPONSE, time: this.clientResponseTime,
        duration: this.clientResponseTime && this.copilotResponseTime ?
          this.clientResponseTime.getTime() - this.copilotResponseTime.getTime() : null }
    ].filter(item => item.time !== null);
  }

  /**
   * 检查请求是否成功完成
   */
  isCompleted(): boolean {
    return this.status === RequestStatus.SUCCESS && 
           this.currentPhase === RequestPhase.CLIENT_RESPONSE &&
           this.clientResponseTime !== null;
  }

  /**
   * 获取错误摘要信息
   */
  getErrorSummary() {
    if (this.status !== RequestStatus.ERROR) {
      return null;
    }
    
    return {
      phase: this.errorPhase,
      message: this.errorMessage,
      hasStack: !!this.errorStack
    };
  }

  /**
   * 获取性能摘要
   */
  getPerformanceSummary() {
    return {
      totalDuration: this.totalDuration,
      conversionDuration: this.conversionDuration, 
      apiDuration: this.copilotApiDuration,
      inputTokens: this.actualInputTokens || this.estimatedInputTokens,
      outputTokens: this.actualOutputTokens || this.estimatedOutputTokens,
      retryCount: this.retryCount
    };
  }
}